<template>
  <div class="user-info-head">
    <el-dialog
      :title="title"
      v-model="open"
      width="800px"
      append-to-body
      @close="closeDialog"
    >
      <el-row>
        <el-col :xs="24" :md="12" :style="{ height: '500px' }">
          <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :outputType="options.outputType"
            @realTime="realTime"
          />
        </el-col>

        <el-col :xs="24" :md="12" :style="{ height: '200px' }">
          <div class="avatar-upload-preview">
            <img :src="options.previews.url" />
          </div>
        </el-col>
      </el-row>

      <br />

      <el-row justify="space-between" align="middle">
        <el-col :span="2">
          <el-upload
            action="#"
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <el-button>
              选择
              <el-icon class="el-icon--right"><Upload /></el-icon>
            </el-button>
          </el-upload>
        </el-col>

        <el-col :span="1" :offset="2">
          <el-button :icon="Plus" @click="changeScale(1)" />
        </el-col>

        <el-col :span="1" :offset="1">
          <el-button :icon="Minus" @click="changeScale(-1)" />
        </el-col>

        <el-col :span="1" :offset="1">
          <el-button :icon="RefreshLeft" @click="rotateLeft" />
        </el-col>

        <el-col :span="1" :offset="1">
          <el-button :icon="RefreshRight" @click="rotateRight" />
        </el-col>

        <el-col :span="2" :offset="6">
          <el-button type="primary" @click="uploadImg">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, getCurrentInstance, inject } from "vue";
import "vue-cropper/dist/index.css";
import { VueCropper } from "vue-cropper";
import { ElMessage } from "element-plus";
import {
  Upload,
  Plus,
  Minus,
  RefreshLeft,
  RefreshRight,
} from "@element-plus/icons-vue";

import { uploadFiles } from "@/api/business/upload";
import { updatePhoto, getPhotoListByType } from "@/api/business/egg";
import { useUserStore } from "@/store/modules/user";

const userId = inject("userId");
const emits = defineEmits(["closeDialog"]);
const props = defineProps({
  visiable: {
    type: Boolean,
    required: true,
    default: false,
  },
  donorId: {
    type: String,
    required: true,
    default: "",
  },
  userName: {
    type: String,
    required: true,
    default: "",
  },
});

const userStore = useUserStore();
const { proxy } = getCurrentInstance();

const open = ref(false);
const title = ref("修改缩略图");

// 图片裁剪数据
const options = reactive({
  img: "",
  autoCrop: true,
  autoCropWidth: 317,
  autoCropHeight: 200,
  fixedBox: true,
  outputType: "png",
  filename: "avatar",
  previews: {},
});

/* 覆盖默认上传行为 */
function requestUpload() {}

/* 向左旋转 */
function rotateLeft() {
  proxy.$refs.cropper.rotateLeft();
}

/* 向右旋转 */
function rotateRight() {
  proxy.$refs.cropper.rotateRight();
}

/* 图片缩放 */
function changeScale(num = 1) {
  proxy.$refs.cropper.changeScale(num);
}

/* 上传预处理 */
function beforeUpload(file) {
  if (!file.type.startsWith("image/")) {
    ElMessage.error("文件格式错误，请上传图片类型，如 JPG、PNG 后缀的文件。");
    return false;
  }
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    options.img = reader.result;
    options.filename = file.name;
  };
  return false; // 阻止 el-upload 自动上传
}

/* 上传图片 */
function uploadImg() {
  proxy.$refs.cropper.getCropBlob((data) => {
    const formData = new FormData();
    formData.append("files", data, options.filename);
    const uploadUrl = `/business/photo/uploads?username=${props.userName}`;
    uploadFiles(formData, uploadUrl).then((response) => {
      options.img = response.urls;
      updateForm({
        photoUrls: response.urls,
        basicId: props.donorId,
        photoType: "缩略图",
      });
    });
  });
}

const updateForm = async (form) => {
  updatePhoto(form).then((resp) => {
    if (resp.code === 200) {
      ElMessage.success("上传成功");
      closeDialog();
    } else {
      ElMessage.error("上传失败");
    }
  });
};

/* 实时预览 */
function realTime(data) {
  options.previews = data;
}

/* 关闭窗口 */
function closeDialog() {
  emits("closeDialog");
}

watch(
  () => props.visiable,
  (val) => {
    open.value = val;
    if (val) {
      getPhotoListByType({ donorId: props.donorId ,photoType:'缩略图'}).then((res) => {
        options.img =
          res.rows && res.rows.length > 0 ? res.rows[0].photoUrl : "";
      });
    }
  },
  { deep: true, immediate: true }
);
</script>

<style lang="scss" scoped>
.user-info-head {
  position: relative;
  display: inline-block;
  height: 200px;

  &:hover::after {
    content: "+";
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    color: #eee;
    background: rgba(0, 0, 0, 0.5);
    font-size: 24px;
    font-style: normal;
    cursor: pointer;
    line-height: 110px;
  }
}

.avatar-upload-preview {
  width: 317px;
  height: 200px;
  border-radius: 0;
  top: 0;
  transform: translate(0, 0);
  right: 0;

  img {
    width: 100%;
    height: 100%;
  }
}
</style>
